#include "Config.h"
#include "monitor_public_def.h"
#include "BusWorker.h"
#include "Client.h"
#include "ChipLog.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <boost/thread.hpp>
#include <boost/asio.hpp>


int main(int argc, char* argv[])
{
	CConfig*pConfig = CConfig::Instance();

	if (!pConfig || !pConfig->LoadSetting())
	{
		std::cerr << "load config failed!" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(2));
		return 0;
	}
	std::cout << "load config success!" << std::endl;



	std::string strLog = GetAppPath();
#ifdef WIN32
	strLog += "logs\\CollectChipData.log";
#else
	strLog += "logs/CollectChipData.log";
#endif
	if (!CChipLog::Instance()->InitLogEnv(strLog.c_str(), pConfig->_chipcfg.nLoglvl, pConfig->_chipcfg.nLogSize))
	{
		std::cerr << "Init Log failed!" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(2));
		return 0;
	}

	std::cout << "Init Log  success!" << std::endl;


	std::shared_ptr<CBusWorker> pWorker = std::make_shared<CBusWorker>();
	if (!pWorker || !pWorker->StartService(pConfig->_chipcfg._mqServer))
	{
		std::cerr << "mqservice start failed!" << std::endl;
		CChipLog::Instance()->WriteLog(LogLvlError, "mqservice start failed!");
		std::this_thread::sleep_for(std::chrono::seconds(2));
		return 0;
	}
	std::cout << "mqservice start   success!" << std::endl;


	std::list<std::shared_ptr<Client>> clients;
	boost::asio::io_service m_ioService;
	boost::asio::io_service::work wk(m_ioService);
	boost::thread_group threadGroup;


	for (auto& itsrv: pConfig->_chipcfg._servers)
	{
		for (auto & itCode : pConfig->_chipcfg._stocks)
		{
			std::shared_ptr<Client> clientPtr = std::make_shared<Client>(m_ioService, itsrv, itCode, pConfig->_chipcfg.nInterval, pConfig->_chipcfg.nRetry);
			clients.emplace_back(clientPtr);

			m_ioService.post([clientPtr, pWorker]{
				clientPtr->StartWorker( [pWorker](std::string && result){
				pWorker->Push2Bus(std::forward<std::string >(result));
			});
			});
		}
	}


	for (int i = 0; i < pConfig->_chipcfg.nThreadNum;i++)	
		threadGroup.create_thread([&m_ioService]{m_ioService.run(); });
	
	threadGroup.join_all();

	return 0;
}